<template>
  <div class="category-management">
    <div class="page-header">
      <h2>商品分类管理</h2>
      <div>
        <button class="btn btn-primary" @click="showCreateModal">➕ 新增分类</button>
        <button class="btn btn-primary" @click="loadCategories">🔄 刷新</button>
      </div>
    </div>

    <!-- 分类列表 -->
    <div class="card">
      <div v-if="loading" class="loading">加载中...</div>
      
      <div v-else-if="categories.length === 0" class="empty">
        暂无分类数据
      </div>

      <div v-else>
        <table>
          <thead>
            <tr>
              <th>ID</th>
              <th>分类名称</th>
              <th>描述</th>
              <th>排序</th>
              <th>状态</th>
              <th>创建时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="category in categories" :key="category.id">
              <td>{{ category.id }}</td>
              <td>{{ category.name }}</td>
              <td>{{ category.description || '-' }}</td>
              <td>{{ category.sort_order }}</td>
              <td>
                <span :class="['status-tag', category.status === 1 ? 'status-paid' : 'status-cancelled']">
                  {{ category.status === 1 ? '启用' : '禁用' }}
                </span>
              </td>
              <td>{{ formatDate(category.created_at) }}</td>
              <td>
                <div class="actions">
                  <button class="btn btn-default btn-sm" @click="editCategory(category)">
                    编辑
                  </button>
                  <button class="btn btn-danger btn-sm" @click="deleteCategory(category)">
                    删除
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 创建/编辑弹窗 -->
    <div v-if="showModal" class="modal" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ editingCategory ? '编辑分类' : '新增分类' }}</h3>
          <button class="close-btn" @click="closeModal">✕</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>分类名称 *</label>
            <input v-model="formData.name" type="text" placeholder="请输入分类名称" />
          </div>
          <div class="form-group">
            <label>描述</label>
            <textarea v-model="formData.description" placeholder="请输入描述"></textarea>
          </div>
          <div class="form-group">
            <label>排序</label>
            <input v-model.number="formData.sort_order" type="number" placeholder="数字越小越靠前" />
          </div>
          <div class="form-group">
            <label>状态</label>
            <select v-model.number="formData.status">
              <option :value="1">启用</option>
              <option :value="0">禁用</option>
            </select>
          </div>
          <div class="form-actions">
            <button class="btn btn-default" @click="closeModal">取消</button>
            <button class="btn btn-primary" @click="submitForm">确定</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getCategories, createCategory, updateCategory, deleteCategory as deleteCategoryApi } from '../api/category';

const categories = ref([]);
const loading = ref(false);
const showModal = ref(false);
const editingCategory = ref(null);
const formData = ref({
  name: '',
  description: '',
  sort_order: 0,
  status: 1
});

const loadCategories = async () => {
  loading.value = true;
  try {
    const res = await getCategories();
    if (res.success) {
      categories.value = res.data.list || res.data;
    } else {
      alert(res.message || '加载失败');
    }
  } catch (error) {
    console.error('加载分类失败:', error);
    alert('网络错误: ' + (error.message || '未知错误'));
  } finally {
    loading.value = false;
  }
};

const formatDate = (dateStr) => {
  if (!dateStr) return '-';
  return dateStr.replace('T', ' ').substring(0, 19);
};

const showCreateModal = () => {
  editingCategory.value = null;
  formData.value = {
    name: '',
    description: '',
    sort_order: 0,
    status: 1
  };
  showModal.value = true;
};

const editCategory = (category) => {
  editingCategory.value = category;
  formData.value = {
    name: category.name,
    description: category.description,
    sort_order: category.sort_order,
    status: category.status
  };
  showModal.value = true;
};

const closeModal = () => {
  showModal.value = false;
  editingCategory.value = null;
};

const submitForm = async () => {
  if (!formData.value.name) {
    alert('请输入分类名称');
    return;
  }

  try {
    let res;
    if (editingCategory.value) {
      res = await updateCategory(editingCategory.value.id, formData.value);
    } else {
      res = await createCategory(formData.value);
    }

    if (res.success) {
      alert('操作成功');
      closeModal();
      loadCategories();
    } else {
      alert(res.message || '操作失败');
    }
  } catch (error) {
    console.error('提交失败:', error);
    alert('网络错误: ' + (error.message || '未知错误'));
  }
};

const deleteCategory = async (category) => {
  if (!confirm(`确定要删除分类"${category.name}"吗？`)) return;

  try {
    const res = await deleteCategoryApi(category.id);
    if (res.success) {
      alert('删除成功');
      loadCategories();
    } else {
      alert(res.message || '删除失败');
    }
  } catch (error) {
    console.error('删除失败:', error);
    alert('网络错误: ' + (error.message || '未知错误'));
  }
};

onMounted(() => {
  loadCategories();
});
</script>

<style scoped>
.category-management {
  max-width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.page-header div {
  display: flex;
  gap: 12px;
}

.actions {
  display: flex;
  gap: 8px;
}

.btn-sm {
  padding: 4px 12px;
  font-size: 12px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
}

.form-group input,
.form-group textarea,
.form-group select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  font-size: 14px;
}

.form-group textarea {
  min-height: 80px;
  resize: vertical;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e5e5e5;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
}

.close-btn:hover {
  background: #f5f5f5;
  color: #333;
}

.modal-body {
  padding: 20px;
}
</style>

